const fs = require('fs')
const path = require('path')
const KoaRouter = require('koa-router')
const mock = require('./data/MockData')
const { resSuccess, resError, sleep } = require('./utils')
const router = new KoaRouter()
const stream = require('stream')

/**
 * 1-普通请求
 */
// 1.1 get
router.get('/get/listData', (ctx) => {
  ctx.body = resSuccess(1)
})
// 1.2 post
router.post('/post/cityList', (ctx) => {
  ctx.body = resSuccess(ctx.request.body)
})
// 1.3 文件上传
router.post('/upload/file', (ctx) => {
  const file = ctx.request.files.file
  if (!file) {
    return (ctx.body = this.resError('请上传文件 上传字段为 file'))
  }
  // 文件流写入操作... 略
  ctx.body = resSuccess(`${file.name} 上传成功`)
})
/**
 * 2-请求失败
 */
router.get('/fail', (ctx) => {
  ctx.body = resError('查询失败')
})
/**
 * 3-服务器异常
 */
// 3.1 响应异常
router.get('/resError', (ctx) => {
  throw '模拟代码写错'
})
// 3.1 响应超时
router.get('/resTimeout', async (ctx) => {
  const t = ctx.query.time || 8000
  await sleep(t)
  ctx.body = resSuccess(t + ' 秒后才返回')
})
/**
 * 4-接口返回格式不统一
 */
// 4.1 返回的对象键不确定
router.get('/resRandom', (ctx) => {
  const n = Math.random()
  if (n > 0.6) {
    ctx.body = { code: 0 }
  } else if (n > 0.3) {
    ctx.body = resSuccess(1)
  } else {
    ctx.body = { data: 2 }
  }
})
// 4.2 get 返回文件流
router.get('/file-stream', (ctx) => {
  const fileName = '156-万花筒.zip'
  ctx.set('Content-Disposition', `attachment; filename=${encodeURIComponent(fileName)}`)
  ctx.body = new stream.Readable({
    async read() {
      const src = path.resolve(__dirname, `./data/${fileName}`)
      const reader = fs.createReadStream(src)
      reader.on('data', (chunk) => this.push(chunk))
      reader.on('close', () => this.push(null))
    }
  })
})

// ===== 中间件功能测试 =====
// 接口缓存-列表数据
router.get('/api/listData', (ctx) => {
  ctx.body = resSuccess(mock.listData(ctx.query.count))
})
// 接口防抖-评论列表
router.get('/api/commentList', async (ctx) => {
  await sleep(800)
  ctx.body = resSuccess(mock.commentList(50))
})
// ===== 模拟业务接口测试 =====
// 登录
router.post('/user/login', (ctx) => {
  const { username, password } = ctx.request.body
  if (!username) {
    ctx.body = resError('用户名不能为空!')
    return
  }
  if (!password) {
    ctx.body = resError('密码不能为空!')
    return
  }
  ctx.body = resSuccess({
    username: username,
    token: '123456'
  })
})

module.exports = router
